<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleDownload"
          class="custom-download-btn"
        >
          下载
        </el-button>
      </el-col>
      <el-col :span="3">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入搜索关键词"
          clearable
          class="custom-input"
        />
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleSearch"
          class="custom-search-btn"
        >
          搜索
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          class="custom-add-btn"
        >
          新增
        </el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="gelikgList"
      class="custom-table"
      border
      resizable
    >
      <!-- 循环渲染表格列，根据不同列设置不同宽度 -->
      <el-table-column
        v-for="(column, index) in tableColumns"
        :key="index"
        :label="column.label"
        :prop="column.prop"
        :formatter="column.formatter"
        :width="column.width" 
      />
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleEdit(scope.row)"
            class="custom-edit-btn"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            class="custom-delete-btn"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      :page-sizes="[5, 10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="custom-pagination"
    />

    <el-dialog
      :title="isEdit ? '编辑隔离开关记录' : '新增隔离开关记录'"
      :visible.sync="dialogVisible"
      width="50%"
      class="custom-dialog"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item
          v-for="(field, index) in formFields"
          :key="index"
          :label="field.label"
          :prop="field.prop"
        >
          <el-input
            v-if="field.type !== 'date'"
            v-model="form[field.prop]"
            class="custom-input"
          />
          <el-date-picker
            v-else
            v-model="form[field.prop]"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            class="custom-datepicker"
          />
        </el-form-item>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" class="custom-cancel-btn">
            取 消
          </el-button>
          <el-button type="primary" @click="submitForm" class="custom-confirm-btn">
            确 定
          </el-button>
        </span>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import {
  selectAll,
  deleteGelikg,
  downloadGelikg,
  addGelikg,
  updateGelikg,
} from "@/api/MaintenanceRecord/gelikg";
import dayjs from "dayjs";

export default {
  name: "GelikgList",
  data() {
    return {
      loading: true,
      gelikgList: [],
      allList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchKeyword: "",
      tableColumns: [
        { label: "隔离开关ID编号", prop: "kgid" ,width: '100'},
        { label: "设备名称", prop: "equipname",width: '100' },
        { label: "战区名称", prop: "zqname" ,width: '100'},
        { label: "工区名称", prop: "gongquName",width: '100' },
        { label: "杆号", prop: "ganhaos",width: '100' },
        { label: "分闸角度", prop: "fzjd",width: '100' },
        { label: "合闸角度", prop: "hzjd",width: '100' },
        { label: "接触状态", prop: "jczt",width: '100' },
        { label: "线接触塞入深度", prop: "scXsd",width: '100' },
        { label: "面宽50mm以下塞入深度", prop: "scMlsd" ,width: '100'},
        { label: "面宽50mm以上塞入深度", prop: "scMusd" ,width: '100'},
        { label: "止钉间隙", prop: "zdjx" ,width: '100'},
        { label: "接地刀闸接触状态", prop: "jddzJczt" ,width: '100'},
        { label: "接地刀闸与带电体距离", prop: "jddzDdt" ,width: '100'},
        { label: "操作机构和联锁装置状态", prop: "czjg" ,width: '100'},
        { label: "设备线夹连接状态", prop: "sbxj" ,width: '100'},
        { label: "电联结及引线状态", prop: "dlj" ,width: '100'},
        { label: "远动开合情况", prop: "ydkh" ,width: '100'},
        { label: "绝缘状态", prop: "jyzt" ,width: '100'},
        { label: "负责人", prop: "leader" ,width: '100'},
        { label: "操作者", prop: "oprator" ,width: '100'},
        { label: "操作日期", prop: "opdate", formatter: this.formatDate ,width: '100'},
        { label: "是否打水印", prop: "watermark" ,width: '100'},
        { label: "是否最新", prop: "islast" ,width: '100'},
        { label: "备注", prop: "remark" ,width: '100'},
      ],
      dialogVisible: false,
      isEdit: false,
      form: {
        kgid: null,
        eqId: null,
        zqId: null,
        baseKgid: null,
        ganhaos: "",
        fzjd: null,
        hzjd: null,
        jczt: "",
        scXsd: null,
        scMlsd: null,
        scMusd: null,
        zdjx: null,
        jddzJczt: "",
        jddzDdt: null,
        czjg: "",
        sbxj: "",
        dlj: "",
        ydkh: "",
        jyzt: "",
        leader: "",
        oprator: "",
        opdate: "",
        watermark: null,
        islast: null,
        remark: "",
      },
      rules: {
        eqId: [{ required: true, message: "请输入 eq_id", trigger: "blur" }],
        zqId: [{ required: true, message: "请输入 zq_id", trigger: "blur" }],
        baseKgid: [
          { required: true, message: "请输入 base_kgid", trigger: "blur" },
        ],
        ganhaos: [
          { required: true, message: "请输入 ganhaos", trigger: "blur" },
        ],
        fzjd: [{ required: true, message: "请输入分闸角度", trigger: "blur" }],
        hzjd: [{ required: true, message: "请输入合闸角度", trigger: "resize" }],
        jczt: [{ required: true, message: "请输入接触状态", trigger: "blur" }],
        scXsd: [
          { required: true, message: "请输入线接触塞入深度", trigger: "blur" },
        ],
        scMlsd: [
          {
            required: true,
            message: "请输入面宽50mm以下塞入深度",
            trigger: "blur",
          },
        ],
        scMusd: [
          {
            required: true,
            message: "请输入面宽50mm以上塞入深度",
            trigger: "blur",
          },
        ],
        zdjx: [{ required: true, message: "请输入止钉间隙", trigger: "blur" }],
        jddzJczt: [
          {
            required: true,
            message: "请输入接地刀闸接触状态",
            trigger: "blur",
          },
        ],
        jddzDdt: [
          {
            required: true,
            message: "请输入接地刀闸与带电体距离",
            trigger: "blur",
          },
        ],
        czjg: [
          {
            required: true,
            message: "请输入操作机构和联锁装置状态",
            trigger: "blur",
          },
        ],
        sbxj: [
          {
            required: true,
            message: "请输入设备线夹连接状态",
            trigger: "blur",
          },
        ],
        dlj: [
          {
            required: true,
            message: "请输入电联结及引线状态",
            trigger: "blur",
          },
        ],
        ydkh: [
          { required: true, message: "请输入远动开合情况", trigger: "blur" },
        ],
        jyzt: [{ required: true, message: "请输入绝缘状态", trigger: "blur" }],
        leader: [{ required: true, message: "请输入负责人", trigger: "blur" }],
        oprator: [{ required: true, message: "请输入操作者", trigger: "blur" }],
        opdate: [
          { required: true, message: "请选择操作日期", trigger: "blur" },
        ],
        watermark: [
          { required: true, message: "请选择是否打水印", trigger: "blur" },
        ],
        islast: [
          { required: true, message: "请选择是否最新", trigger: "blur" },
        ],
        remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
      },
      formFields: [
        { label: "隔离开关ID编号", prop: "kgid", type: "input", disabled: true },
        { label: "eq_id", prop: "eqId", type: "input" },
        { label: "zq_id", prop: "zqId", type: "input" },
        { label: "base_kgid", prop: "baseKgid", type: "input" },
        { label: "ganhaos", prop: "ganhaos", type: "input" },
        { label: "分闸角度", prop: "fzjd", type: "input" },
        { label: "合闸角度", prop: "hzjd", type: "input" },
        { label: "接触状态", prop: "jczt", type: "input" },
        { label: "线接触塞入深度", prop: "scXsd", type: "input" },
        { label: "面宽50mm以下塞入深度", prop: "scMlsd", type: "input" },
        { label: "面宽50mm以上塞入深度", prop: "scMusd", type: "input" },
        { label: "止钉间隙", prop: "zdjx", type: "input" },
        { label: "接地刀闸接触状态", prop: "jddzJczt", type: "input" },
        { label: "接地刀闸与带电体距离", prop: "jddzDdt", type: "input" },
        { label: "操作机构和联锁装置状态", prop: "czjg", type: "input" },
        { label: "设备线夹连接状态", prop: "sbxj", type: "input" },
        { label: "电联结及引线状态", prop: "dlj", type: "input" },
        { label: "远动开合情况", prop: "ydkh", type: "input" },
        { label: "绝缘状态", prop: "jyzt", type: "input" },
        { label: "负责人", prop: "leader", type: "input" },
        { label: "操作者", prop: "oprator", type: "input" },
        { label: "操作日期", prop: "opdate", type: "date" },
        { label: "是否打水印", prop: "watermark", type: "select" },
        { label: "是否最新", prop: "islast", type: "select" },
        { label: "备注", prop: "remark", type: "input" },
      ],
    };
  },
  computed: {
    filteredList() {
      if (!this.searchKeyword) return this.allList;
      const keyword = this.searchKeyword.toLowerCase();
      return this.allList.filter((item) =>
        Object.values(item).some((value) =>
          String(value).toLowerCase().includes(keyword)
        )
      );
    },
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      selectAll()
        .then((response) => {
          this.allList = response.data;
          this.total = this.allList.length;
          this.currentPage = 1;
          this.updateGelikgList();
          this.loading = false;
        })
        .catch((error) => {
          console.error("接口请求出错:", error);
          this.loading = false;
        });
    },
    updateGelikgList() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.gelikgList = this.filteredList.slice(start, end);
    },
    handleDelete(row) {
      this.$confirm("确认删除该记录吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteGelikg(row.kgid)
            .then(() => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.fetchData();
            })
            .catch((error) => {
              console.error("删除失败:", error);
              this.$message({
                type: "error",
                message: "删除失败",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.updateGelikgList();
    },
    handleDownload() {
      downloadGelikg()
        .then((response) => {
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", "隔离开关记录数据.xlsx");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch((error) => {
          console.error("下载失败:", error);
        });
    },
    handleSearch() {
      this.currentPage = 1;
      this.fetchData();
    },
    formatDate(row, column, cellValue, index) {
      return dayjs(cellValue).format("YYYY-MM-DD");
    },
    handleEdit(row) {
      this.isEdit = true;
      this.form = { ...row };
      this.dialogVisible = true;
    },
    handleAdd() {
      this.isEdit = false;
      this.form = {
        kgid: null,
        eqId: null,
        zqId: null,
        baseKgid: null,
        ganhaos: "",
        fzjd: null,
        hzjd: null,
        jczt: "",
        scXsd: null,
        scMlsd: null,
        scMusd: null,
        zdjx: null,
        jddzJczt: "",
        jddzDdt: null,
        czjg: "",
        sbxj: "",
        dlj: "",
        ydkh: "",
        jyzt: "",
        leader: "",
        oprator: "",
        opdate: "",
        watermark: null,
        islast: null,
        remark: "",
      };
      this.dialogVisible = true;
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            updateGelikg(this.form.kgid, this.form)
              .then(() => {
                this.$message.success("编辑成功");
                this.fetchData();
                this.dialogVisible = false;
              })
              .catch((error) => {
                console.error("编辑失败:", error);
                this.$message.error("编辑失败");
              });
          } else {
            addGelikg(this.form)
              .then(() => {
                this.$message.success("新增成功");
                this.fetch咚Data();
                this.dialogVisible = false;
              })
              .catch((error) => {
                console.error("新增失败:", error);
                this.$message.error("新增失败");
              });
          }
        } else {
          this.$message.warning("请填写所有必填字段");
          return false;
        }
      });
    },
  },
};
</script>
<style scoped>
.custom-table {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
  }
.custom-table.el-table__header th {
    background-color: #f5f7fa;
    color: #303133;
    font-weight: bold;
  }
.custom-table.el-table__body tr {
    height: 40px;
  }
.custom-table.el-table__body td {
    color: #606266;
  }
.custom-download-btn {
    background-color: #67c23a;
    color: #fff;
    border: none;
    border-radius: 4px;
  }
.custom-download-btn:hover {
    background-color: #85ce61;
  }
.custom-search-btn,.custom-add-btn {
    background-color: #409EFF;
    color: #fff;
    border: none;
    border-radius: 4px;
  }
.custom-search-btn:hover,.custom-add-btn:hover {
    background-color: #66b1ff;
  }
.custom-input {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 5px;
    background-color: #f5f7fa;
  }
.custom-input:hover,.custom-input:focus {
    border-color: #409EFF;
  }
.custom-edit-btn,.custom-delete-btn {
    color: #409EFF;
  }
.custom-edit-btn:hover,.custom-delete-btn:hover {
    color: #66b1ff;
  }
.custom-pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
.custom-pagination.el-pagination button,.custom-pagination.el-pagination span {
    font-size: 14px;
    color: #606266;
  }
.custom-pagination.el-pagination.el-pager li {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin: 0 5px;
  }
.custom-pagination.el-pagination.el-pager li:hover {
    color: #409EFF;
    border-color: #409EFF;
  }
.custom-dialog {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    background-color: #fff;
  }
.custom-datepicker {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 5px;
    background-color: #f5f7fa;
  }
.custom-datepicker:hover,.custom-datepicker:focus {
    border-color: #409EFF;
  }
.custom-select {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 5px;
    background-color: #f5f7fa;
  }
.custom-select:hover,.custom-select:focus {
    border-color: #409EFF;
  }
.custom-cancel-btn {
    background-color: #e4e7ed;
    color: #606266;
    border: none;
    border-radius: 4px;
  }
.custom-cancel-btn:hover {
    background-color: #d1dbe5;
  }
.custom-confirm-btn {
    background-color: #409EFF;
    color: #fff;
    border: none;
    border-radius: 4px;
  }
.custom-confirm-btn:hover {
    background-color: #66b1ff;
  }
</style>